import codecs
import os
import PyPDF2 as PyPDF2

def mergePdf(path,files,saveName): 
	pdfwriter = PyPDF2.PdfFileWriter()
	for item in files:
		pdfreader = PyPDF2.PdfFileReader(open(path + '/' + item,"rb"))
		for page in range(pdfreader.numPages):
			pdfwriter.addPage(pdfreader.getPage(page))
	
	with codecs.open(saveName,"wb") as f:
		pdfwriter.write(f)


def main():
	pdfUrl = "mergefrom"
	pdftoUrl = "mergeto"
	if not os.path.exists(pdftoUrl):
		os.makedirs(pdftoUrl)
	fileList = os.listdir(pdfUrl)
	index = 1
	for itemdir in  fileList:
		files = os.listdir(pdfUrl + "/" + itemdir)
		saveName = pdftoUrl + "/" + itemdir
		if not os.path.exists(saveName):
			os.makedirs(saveName)
		checkfiles = None
		try:
			newfiles = sorted(files,key=lambda d: int(d.split(".pdf")[0]))
			checkfiles = newfiles
		except Exception as e:
			checkfiles = files
		path = pdfUrl + "/" + itemdir
		mergePdf(path,checkfiles,saveName + "/" + itemdir + ".pdf")
		print("合并成功," + str(index))
		index+=1
	print("合并完成成功，请在mergeto文件夹中寻找合并成功的文件")
	input()


if __name__ == "__main__":
    main()